from geopy.geocoders import Nominatim
from urllib.parse import urljoin
from lxml import etree
import pandas as pd
import numpy as np
import json
import requests
# -*- coding: utf-8 -*-
# @Time        : 2023/11/18
# @Author      : keyan.kalami
# @Email       : yclu@aioaiofm.ac.cn
# @File        : geo.py
# @Project     : geo
# @Description : 根据百度地图查询地理信息

with open('/root/Programs/NovaPrograms/set/_ads.json', 'r', encoding='utf-8') as file:  
    VALUE_SETS = json.load(file)

class Baidu_Map:
    def __init__(self):
        self.url = VALUE_SETS["GEO_CODE_URL"]
        self.ak = VALUE_SETS["BAIDU_MAP_AK"]
        self.s = requests.Session()

    def get_location(self,latitude:float,longitude:float) -> dict:
        #根据经纬度获取地理位置信息
        params = {
            'ak':   self.ak,
            'output': 'json',
            'coordtype': 'wgs84ll',
            'location': f'{latitude},{longitude}',
        }
        try:
            resp = self.s.get(url=self.url,params=params).json()
            address = resp['result']['addressComponent']
        except:
            print(f'接受address:{latitude},{longitude}位置信息异常')
            return None

        return {
            item:address[item] for item in ['country', 'province', 'city', 'district']
        }
    
# map_obi = Baidu_Map()
# mes=map_obi.get_location(70.9333333,-8.6666667)
# print(mes)

# #创建一个地理编码器的对象
# geolocator = Nominatim(user_agent="MyApp",timeout=15)

# def get_address_from_coordinates(latitude,longitude):
#     location = geolocator.reverse((latitude,longitude),exactly_one=True)
#     if location:
#         print("Latitude and Longitude: {} {}".format(latitude, longitude))
#         print("Location Address:", location.address)
#     else:
#         print("Location not found for the coordinates:", latitude, longitude)

# # 调用函数并传入经纬度信息
# get_address_from_coordinates(40.6892534, -74.0466891)  # 传入纽约自由女神像的经纬度作为示例